///////////////////////////////////////////////////
/// toto Code
/// $Id: mutex.h 2 2009-12-14 12:41:06Z tonyjobmails $
/// $Date: 2009-12-14 12:41:06 +0000 (Mon, 14 Dec 2009) $
/// $Author: tonyjobmails $
/// $Revision: 2 $
/// E-mail: tonyjobmails@gmail.com
/// filename: mutex.h
/// function: 互斥量定义
///////////////////////////////////////////////////

# ifndef __MUTEX__H
#define __MUTEX__H

#include <pthread>

namespace toto
{
	class xmutex
	{
		friend xcond;
		public:
			/***************************************************
			/// 互斥锁类型定义
			enum
			{
				PTHREAD_MUTEX_TIMED_NP,
				PTHREAD_MUTEX_RECURSIVE_NP,
				PTHREAD_MUTEX_ERRORCHECK_NP,
				PTHREAD_MUTEX_ADAPTIVE_NP
			#ifdef __USE_UNIX98
				,
				PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
				PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
				PTHREAD_M UTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
				PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
			#endif
			#ifdef __USE_GNU
				, PTHREAD_MUTEX_FAST_NP = PTHREAD_MUTEX_TIMED_NP
			#endif
			};
			****************************************************/
			xmutex(int kind = PTHREAD_MUTEX_NORMAL)
			{
				pthread_mutexattr_t attr;
				pthread_mutexattr_init(&attr);
				pthread_mutexattr_settype(&attr, kind);
				pthread_mutex_init(&this->mutex, &attr);
				/// pthread_mutexattr_destroy(&attr);
			}
			
			virtual ~xmutex()
			{
				pthread_mutex_destroy(&this->mutex);
			}
			
			/// 加锁
			inline void lock()
			{
				pthread_mutex_lock(&this->mutex);
			}
			
			/// 解锁
			inline void unlock()
			{
				pthread_mutex_unlock(&this->mutex);
			}
			
		private:
			pthread_mutex_t mutex;
	};
};

#endif	/// __MUTEX__H
